<template>
  <div class="tree-select-demo">
    <div class="demo-header">
      <h2>树状下拉多选组件演示</h2>
      <p>功能类似Element UI的树状下拉，支持多级嵌套和级联多选</p>
      <div class="feature-tips">
        <div class="tip-item">
          <strong>级联选择：</strong
          >选择父节点时，所有子节点自动选中；取消父节点时，所有子节点自动取消
        </div>
        <div class="tip-item">
          <strong>智能统计：</strong
          >只统计叶子节点数量，父节点显示半选状态表示部分子节点被选中
        </div>
        <div class="tip-item">
          <strong>状态显示：</strong>✓ 全选、━ 半选、☐ 未选
        </div>
      </div>
    </div>

    <div class="demo-section">
      <h3>基础使用</h3>
      <div class="form-group">
        <label>基础树状多选：</label>
        <TreeSelect
          v-model="basicSelected"
          :options="basicOptions"
          placeholder="请选择部门"
          @change="onBasicChange"
        />
        <div class="selected-values">
          <strong>已选择：</strong>
          <span v-if="basicSelected.length > 0">{{
            getSelectedLabels(basicSelected, basicOptions)
          }}</span>
          <span v-else class="empty">暂无选择</span>
        </div>
      </div>
    </div>

    <div class="demo-section">
      <h3>默认展开所有</h3>
      <div class="form-group">
        <label>默认展开所有节点：</label>
        <TreeSelect
          v-model="expandedSelected"
          :options="categoryOptions"
          placeholder="请选择商品分类"
          :default-expand-all="true"
          @change="onExpandedChange"
        />
        <div class="selected-values">
          <strong>已选择：</strong>
          <span v-if="expandedSelected.length > 0">{{
            getSelectedLabels(expandedSelected, categoryOptions)
          }}</span>
          <span v-else class="empty">暂无选择</span>
        </div>
      </div>
    </div>

    <div class="demo-section">
      <h3>只能选择叶子节点</h3>
      <div class="form-group">
        <label>只能选择最终级别：</label>
        <TreeSelect
          v-model="leafSelected"
          :options="regionOptions"
          placeholder="请选择地区"
          :only-leaf="true"
          @change="onLeafChange"
        />
        <div class="selected-values">
          <strong>已选择：</strong>
          <span v-if="leafSelected.length > 0">{{
            getSelectedLabels(leafSelected, regionOptions)
          }}</span>
          <span v-else class="empty">暂无选择</span>
        </div>
      </div>
    </div>

    <div class="demo-section">
      <h3>禁用状态</h3>
      <div class="form-group">
        <label>禁用状态：</label>
        <TreeSelect
          v-model="disabledSelected"
          :options="basicOptions"
          placeholder="已禁用的下拉"
          :disabled="true"
        />
      </div>
    </div>

    <div class="demo-section">
      <h3>自定义字段名</h3>
      <div class="form-group">
        <label>自定义数据结构（name、id、kids字段）：</label>
        <TreeSelect
          v-model="customSelected"
          :options="customFieldOptions"
          :field-names="{
            label: 'name',
            value: 'id',
            children: 'kids',
          }"
          placeholder="请选择组织架构"
          :default-expand-all="true"
          @change="onCustomChange"
        />
        <div class="selected-values">
          <strong>已选择：</strong>
          <span v-if="customSelected.length > 0">
            {{ getCustomSelectedLabels(customSelected, customFieldOptions) }}
          </span>
          <span v-else class="empty">暂无选择</span>
        </div>
      </div>
    </div>

    <div class="demo-section">
      <h3>综合示例</h3>
      <div class="form-row">
        <div class="form-group">
          <label>权限分配：</label>
          <TreeSelect
            v-model="permissionSelected"
            :options="permissionOptions"
            placeholder="请选择权限"
            :default-expand-all="true"
            @change="onPermissionChange"
          />
        </div>

        <div class="form-group">
          <label>技能标签：</label>
          <TreeSelect
            v-model="skillSelected"
            :options="skillOptions"
            placeholder="请选择技能"
            :only-leaf="true"
            @change="onSkillChange"
          />
        </div>
      </div>

      <div class="result-panel">
        <h4>选择结果（级联选择演示）</h4>
        <div class="result-item">
          <strong>权限 - 全部选中：</strong>
          <span class="count-badge"
            >{{ permissionSelected.length }} 个节点</span
          >
          <div class="tag-list">
            <span
              v-for="value in permissionSelected.slice(0, 10)"
              :key="value"
              class="tag"
            >
              {{ findNodeLabel(value, permissionOptions) }}
            </span>
            <span v-if="permissionSelected.length > 10" class="tag more">
              +{{ permissionSelected.length - 10 }} 更多...
            </span>
          </div>
        </div>
        <div class="result-item">
          <strong>权限 - 叶子节点：</strong>
          <span class="count-badge"
            >{{
              getSelectedLeafLabels(permissionSelected, permissionOptions)
                .length
            }}
            个</span
          >
          <div class="tag-list">
            <span
              v-for="label in getSelectedLeafLabels(
                permissionSelected,
                permissionOptions
              )"
              :key="label"
              class="tag leaf"
            >
              {{ label }}
            </span>
          </div>
        </div>
        <div class="result-item">
          <strong>技能 - 叶子节点：</strong>
          <span class="count-badge"
            >{{
              getSelectedLeafLabels(skillSelected, skillOptions).length
            }}
            个</span
          >
          <div class="tag-list">
            <span
              v-for="label in getSelectedLeafLabels(
                skillSelected,
                skillOptions
              )"
              :key="label"
              class="tag leaf"
            >
              {{ label }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TreeSelect from "@/components/form/treeSelect.vue";

export default {
  name: "TreeSelectDemo",
  components: {
    TreeSelect,
  },
  data() {
    return {
      // 基础选择
      basicSelected: [],

      // 展开选择
      expandedSelected: [],

      // 叶子节点选择
      leafSelected: [],

      // 禁用选择
      disabledSelected: [],

      // 权限选择
      permissionSelected: [],

      // 技能选择
      skillSelected: [],

      // 自定义字段选择
      customSelected: [],

      // 基础选项数据
      basicOptions: [
        {
          label: "技术部",
          value: "tech",
          children: [
            {
              label: "前端组",
              value: "frontend",
              children: [
                { label: "Vue开发", value: "vue" },
                { label: "React开发", value: "react" },
                { label: "Angular开发", value: "angular" },
              ],
            },
            {
              label: "后端组",
              value: "backend",
              children: [
                { label: "Java开发", value: "java" },
                { label: "Python开发", value: "python" },
                { label: "Go开发", value: "go" },
              ],
            },
            {
              label: "移动端组",
              value: "mobile",
              children: [
                { label: "iOS开发", value: "ios" },
                { label: "Android开发", value: "android" },
                { label: "Flutter开发", value: "flutter" },
              ],
            },
          ],
        },
        {
          label: "产品部",
          value: "product",
          children: [
            { label: "产品经理", value: "pm" },
            { label: "UI设计师", value: "ui" },
            { label: "UX设计师", value: "ux" },
          ],
        },
        {
          label: "运营部",
          value: "operation",
          children: [
            { label: "市场推广", value: "marketing" },
            { label: "内容运营", value: "content" },
            { label: "用户运营", value: "user" },
          ],
        },
      ],

      // 商品分类
      categoryOptions: [
        {
          label: "数码电器",
          value: "digital",
          children: [
            {
              label: "手机通讯",
              value: "phone",
              children: [
                { label: "智能手机", value: "smartphone" },
                { label: "老人机", value: "seniorphone" },
                { label: "手机配件", value: "phoneacc" },
              ],
            },
            {
              label: "电脑办公",
              value: "computer",
              children: [
                { label: "笔记本", value: "laptop" },
                { label: "台式机", value: "desktop" },
                { label: "平板电脑", value: "tablet" },
              ],
            },
          ],
        },
        {
          label: "服装鞋靴",
          value: "clothing",
          children: [
            {
              label: "男装",
              value: "mencloth",
              children: [
                { label: "T恤", value: "mentshirt" },
                { label: "衬衫", value: "menshirt" },
                { label: "裤子", value: "menpants" },
              ],
            },
            {
              label: "女装",
              value: "womencloth",
              children: [
                { label: "连衣裙", value: "dress" },
                { label: "上衣", value: "womenshirt" },
                { label: "下装", value: "womenpants" },
              ],
            },
          ],
        },
      ],

      // 地区选项
      regionOptions: [
        {
          label: "华东地区",
          value: "east",
          children: [
            {
              label: "上海市",
              value: "shanghai",
              children: [
                { label: "黄浦区", value: "huangpu" },
                { label: "徐汇区", value: "xuhui" },
                { label: "长宁区", value: "changning" },
              ],
            },
            {
              label: "浙江省",
              value: "zhejiang",
              children: [
                { label: "杭州市", value: "hangzhou" },
                { label: "宁波市", value: "ningbo" },
                { label: "温州市", value: "wenzhou" },
              ],
            },
          ],
        },
        {
          label: "华南地区",
          value: "south",
          children: [
            {
              label: "广东省",
              value: "guangdong",
              children: [
                { label: "广州市", value: "guangzhou" },
                { label: "深圳市", value: "shenzhen" },
                { label: "东莞市", value: "dongguan" },
              ],
            },
            {
              label: "福建省",
              value: "fujian",
              children: [
                { label: "福州市", value: "fuzhou" },
                { label: "厦门市", value: "xiamen" },
                { label: "泉州市", value: "quanzhou" },
              ],
            },
          ],
        },
      ],

      // 权限选项
      permissionOptions: [
        {
          label: "系统管理",
          value: "system",
          children: [
            { label: "用户管理", value: "user_manage" },
            { label: "角色管理", value: "role_manage" },
            { label: "权限管理", value: "permission_manage" },
            { label: "系统配置", value: "system_config" },
          ],
        },
        {
          label: "内容管理",
          value: "content",
          children: [
            { label: "文章管理", value: "article_manage" },
            { label: "分类管理", value: "category_manage" },
            { label: "标签管理", value: "tag_manage" },
            { label: "评论管理", value: "comment_manage" },
          ],
        },
        {
          label: "数据统计",
          value: "statistics",
          children: [
            { label: "访问统计", value: "visit_stats" },
            { label: "用户统计", value: "user_stats" },
            { label: "内容统计", value: "content_stats" },
            { label: "收入统计", value: "income_stats" },
          ],
        },
      ],

      // 技能选项
      skillOptions: [
        {
          label: "编程语言",
          value: "language",
          children: [
            {
              label: "前端",
              value: "frontend_lang",
              children: [
                { label: "JavaScript", value: "javascript" },
                { label: "TypeScript", value: "typescript" },
                { label: "HTML/CSS", value: "html_css" },
              ],
            },
            {
              label: "后端",
              value: "backend_lang",
              children: [
                { label: "Java", value: "java_skill" },
                { label: "Python", value: "python_skill" },
                { label: "Node.js", value: "nodejs" },
                { label: "PHP", value: "php" },
              ],
            },
          ],
        },
        {
          label: "数据库",
          value: "database",
          children: [
            {
              label: "关系型",
              value: "sql",
              children: [
                { label: "MySQL", value: "mysql" },
                { label: "PostgreSQL", value: "postgresql" },
                { label: "Oracle", value: "oracle" },
              ],
            },
            {
              label: "非关系型",
              value: "nosql",
              children: [
                { label: "MongoDB", value: "mongodb" },
                { label: "Redis", value: "redis" },
                { label: "Elasticsearch", value: "elasticsearch" },
              ],
            },
          ],
        },
      ],

      // 自定义字段名选项（使用name、id、kids字段）
      customFieldOptions: [
        {
          name: "北京总部",
          id: "bj_hq",
          kids: [
            {
              name: "研发中心",
              id: "rd_center",
              kids: [
                { name: "AI团队", id: "ai_team" },
                { name: "大数据团队", id: "bigdata_team" },
                { name: "云计算团队", id: "cloud_team" },
              ],
            },
            {
              name: "产品中心",
              id: "product_center",
              kids: [
                { name: "产品设计", id: "product_design" },
                { name: "用户体验", id: "user_experience" },
                { name: "产品运营", id: "product_ops" },
              ],
            },
          ],
        },
        {
          name: "上海分公司",
          id: "sh_branch",
          kids: [
            {
              name: "销售部",
              id: "sales_dept",
              kids: [
                { name: "华东销售", id: "east_sales" },
                { name: "华南销售", id: "south_sales" },
                { name: "大客户销售", id: "enterprise_sales" },
              ],
            },
            {
              name: "市场部",
              id: "marketing_dept",
              kids: [
                { name: "品牌推广", id: "brand_promotion" },
                { name: "数字营销", id: "digital_marketing" },
                { name: "公关媒体", id: "pr_media" },
              ],
            },
          ],
        },
        {
          name: "深圳分公司",
          id: "sz_branch",
          kids: [
            {
              name: "技术支持",
              id: "tech_support",
              kids: [
                { name: "客服支持", id: "customer_support" },
                { name: "技术咨询", id: "tech_consulting" },
                { name: "系统维护", id: "system_maintenance" },
              ],
            },
          ],
        },
      ],
    };
  },
  methods: {
    // 基础选择变化
    onBasicChange(values) {},

    // 展开选择变化
    onExpandedChange(values) {},

    // 叶子选择变化
    onLeafChange(values) {},

    // 权限选择变化
    onPermissionChange(values) {},

    // 技能选择变化
    onSkillChange(values) {},

    // 自定义字段选择变化
    onCustomChange(values) {},

    // 获取选中值的标签
    getSelectedLabels(values, options) {
      return values
        .map((value) => this.findNodeLabel(value, options))
        .join(", ");
    },

    // 查找节点标签
    findNodeLabel(value, options) {
      const findNode = (nodes) => {
        for (const node of nodes) {
          if (node.value === value) {
            return node.label;
          }
          if (node.children) {
            const found = findNode(node.children);
            if (found) return found;
          }
        }
        return null;
      };
      return findNode(options) || value;
    },

    // 获取选中的叶子节点标签
    getSelectedLeafLabels(values, options) {
      const leafNodes = this.getLeafNodes(options);
      const selectedLeafValues = values.filter((value) =>
        leafNodes.some((leaf) => leaf.value === value)
      );
      return selectedLeafValues.map((value) =>
        this.findNodeLabel(value, options)
      );
    },

    // 获取所有叶子节点
    getLeafNodes(options) {
      const leafNodes = [];
      const traverse = (nodeList) => {
        nodeList.forEach((node) => {
          if (!node.children || node.children.length === 0) {
            leafNodes.push(node);
          } else {
            traverse(node.children);
          }
        });
      };
      traverse(options);
      return leafNodes;
    },

    // 获取自定义字段的选中值标签
    getCustomSelectedLabels(values, options) {
      return values
        .map((value) => this.findCustomNodeLabel(value, options))
        .join(", ");
    },

    // 查找自定义字段节点标签
    findCustomNodeLabel(value, options) {
      const findNode = (nodes) => {
        for (const node of nodes) {
          if (node.id === value) {
            return node.name;
          }
          if (node.kids) {
            const found = findNode(node.kids);
            if (found) return found;
          }
        }
        return null;
      };
      return findNode(options) || value;
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: #4b58dc;

.tree-select-demo {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;

  .demo-header {
    text-align: center;
    margin-bottom: 40px;

    h2 {
      color: #2c3e50;
      margin-bottom: 10px;
      font-size: 28px;
      font-weight: 600;
    }

    p {
      color: #7f8c8d;
      font-size: 16px;
      margin: 0 0 20px 0;
    }

    .feature-tips {
      background: linear-gradient(
        135deg,
        rgba(75, 88, 220, 0.1),
        rgba(255, 255, 255, 0.8)
      );
      border: 1px solid rgba(75, 88, 220, 0.2);
      border-radius: 8px;
      padding: 20px;
      text-align: left;
      max-width: 800px;
      margin: 0 auto;

      .tip-item {
        margin-bottom: 10px;
        font-size: 14px;
        color: #606266;

        &:last-child {
          margin-bottom: 0;
        }

        strong {
          color: @primary-color;
          font-weight: 600;
        }
      }
    }
  }

  .demo-section {
    margin-bottom: 40px;
    background: #fff;
    border-radius: 8px;
    padding: 30px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    h3 {
      margin-top: 0;
      margin-bottom: 20px;
      color: @primary-color;
      font-size: 20px;
      font-weight: 600;
      border-bottom: 2px solid @primary-color;
      padding-bottom: 10px;
    }

    .form-group {
      margin-bottom: 25px;

      label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
        color: #2c3e50;
        font-size: 14px;
      }

      .selected-values {
        margin-top: 10px;
        padding: 10px;
        background-color: #f8f9fa;
        border-radius: 4px;
        font-size: 14px;
        color: #495057;

        .empty {
          color: #6c757d;
          font-style: italic;
        }
      }
    }

    .form-row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 30px;

      @media (max-width: 768px) {
        grid-template-columns: 1fr;
      }
    }

    .result-panel {
      margin-top: 30px;
      padding: 20px;
      background: linear-gradient(
        135deg,
        rgba(75, 88, 220, 0.1),
        rgba(255, 255, 255, 0.8)
      );
      border-radius: 8px;
      border: 1px solid rgba(75, 88, 220, 0.2);

      h4 {
        margin-top: 0;
        margin-bottom: 15px;
        color: @primary-color;
        font-size: 16px;
      }

      .result-item {
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 0;
        }

        strong {
          display: inline-block;
          min-width: 120px;
          color: #2c3e50;
          margin-right: 10px;
        }

        .count-badge {
          display: inline-block;
          background: rgba(75, 88, 220, 0.1);
          color: @primary-color;
          padding: 2px 8px;
          border-radius: 10px;
          font-size: 12px;
          font-weight: 500;
          margin-right: 10px;
        }

        .tag-list {
          display: block;
          margin-top: 5px;

          .tag {
            display: inline-block;
            background: linear-gradient(
              135deg,
              @primary-color,
              lighten(@primary-color, 20%)
            );
            color: #fff;
            padding: 4px 12px;
            border-radius: 15px;
            font-size: 12px;
            margin-right: 8px;
            margin-bottom: 5px;
            box-shadow: 0 2px 4px rgba(75, 88, 220, 0.3);

            &.leaf {
              background: linear-gradient(
                135deg,
                #52c41a,
                lighten(#52c41a, 20%)
              );
              box-shadow: 0 2px 4px rgba(82, 196, 26, 0.3);
            }

            &.more {
              background: #f0f0f0;
              color: #666;
              box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .tree-select-demo {
    padding: 15px;

    .demo-section {
      padding: 20px;

      .form-row {
        grid-template-columns: 1fr;
        gap: 20px;
      }
    }
  }
}
</style>
